from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

# Create your views here.
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response

from sers.models import Book
from sers.serializer import BookSerializer3
from rest_framework import generics


class BookView(GenericAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer3

    def get(self, request):
        bs = BookSerializer3(instance=self.get_queryset(), many=True)
        return Response(bs.data)

    @csrf_exempt
    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


class BookDetailView(GenericAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer3

    def get(self, request, pk):
        bs = BookSerializer3(instance=self.get_object())
        return Response(bs.data)

    def put(self, request, pk):
        serializer = BookSerializer3(instance=self.get_object(), data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    def delete(self, request, pk):
        self.get_object().delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


class BookViewSon(generics.ListCreateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer3


class BookDetailViewSon(generics.RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer3


from rest_framework.viewsets import ModelViewSet


class BookViewSet(ModelViewSet):
    queryset = Book.objects
    serializer_class = BookSerializer3
    """
        action装饰器的作用：告诉路由类给视图集的自定义方法生成路由信息
        methods, 列表，允许哪些http请求能访问当前视图方法
        detail，布尔，生成路由时是否拼接pk参数
        detail为True，表示路径名格式应该为 book/{pk}/login/
        url_path，字符串，生成路由时末尾路由路径，如果没有声明，则自动以当前方法名作为路由尾缀

        """
    @action(methods=['get'], detail=True, url_path="login")
    def login(self, request, pk):
        return Response({"msg":request.method})

    @action(methods=['get'], detail=False)
    def get_new_5(self, request):
        """获取最新添加的5本书"""
        return Response({"msg":request.method})

